<template>
  <div>
    <!--Breadcrumb面包屑组件-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-alert
          :closable="false"
          title="添加商品信息"
          type="info"
          show-icon
          center
        >
        </el-alert>
      </el-row>
      <el-row class="stepRow">
        <el-steps
          :active="stepsAndTabsActive - 0"
          finish-status="success"
          :space="200"
          align-center
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-row>
      <el-form
        ref="addGoodsTabRef"
        :model="addGoodsTabForm"
        :rules="addGoodsTabFormRules"
        label-position="top"
      >
        <el-tabs
          :before-leave="tabsJump"
          tab-position="left"
          v-model="stepsAndTabsActive"
          @tab-click="tabsClick"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsTabForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsTabForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsTabForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item type="number" label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsTabForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                style="width: 30%"
                clearable
                placeholder="选择商品分类"
                v-model="addGoodsCateSelectedKeys"
                :options="cateList"
                :props="addCateCascaderProp"
                @change="cateChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form>
              <el-form-item
                v-for="item in manyParams"
                :key="item.attr_id"
                :label="item.attr_name"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    border
                    v-for="(itemChildren, index) in item.attr_vals"
                    :label="itemChildren"
                    :key="index"
                  ></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form>
              <el-form-item
                v-for="item in onlyParams"
                :label="item.attr_name"
                :key="item.attr_id"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <!--upload上传组件-->
            <!--action 上传目标接口地址-->
            <!--on-preview 点击预览图片事件-->
            <!--on-remove删除图片事件-->
            <!--file-list文件列表-->
            <!--list-type预览方式-->
            <!--该组件上传图片时的请求是通过其自身封装的请求方法进行的，不会被main.js中的axios拦截器拦截，需要设置headers属性修改请求头-->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="removePics"
              list-type="picture"
              :headers="headersOption"
              :on-success="uploadPics"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!--富文本编辑器组件-->
            <quill-editor v-model="addGoodsTabForm.goods_introduce" />
            <el-row class="addGoodsRow">
              <el-col>
                <el-button type="primary" @click="addGoods"
                  >确 认 添 加</el-button
                >
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog :visible.sync="previewDialog" title="图片预览" width="40%">
      <img class="previewPics" :src="picsUrl" alt="图片预览" />
    </el-dialog>
  </div>
</template>

<script>
// import _ from "lodash" 若使用lodash，这是下载lodash后引入

export default {
  name: "addGoods",
  data() {
    return {
      uploadURL: "https://lianghj.top:8888/api/private/v1/upload",
      picsUrl: "",
      stepsAndTabsActive: "0",
      addGoodsCateSelectedKeys: "",
      previewDialog: false,
      manyParams: [],
      onlyParams: [],
      cateList: [],
      // upload组件绑定的图片上传请求头
      headersOption: {
        Authorization: window.sessionStorage.getItem("token")
      },
      addGoodsTabForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: "",
        goods_introduce: "",
        pics: [],
        attrs: []
      },
      addCateCascaderProp: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      addGoodsTabFormRules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: ["blur", "change"]
          }
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: ["blur", "change"]
          }
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: ["blur", "change"]
          }
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品数量",
            trigger: ["blur", "change"]
          }
        ],
        goods_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    tabsJump(activeName, oldActiveName) {
      if (oldActiveName === "0") {
        if (
          !this.addGoodsTabForm.goods_cat ||
          !this.addGoodsTabForm.goods_name ||
          !this.addGoodsTabForm.goods_price ||
          !this.addGoodsTabForm.goods_weight
        ) {
          this.$message.error("请先完成当前表单");
          return false;
        }
      }
    },
    tabsClick() {
      switch (this.stepsAndTabsActive) {
        case "1": {
          this.getParams("many");
          break;
        }
        case "2": {
          this.getParams("only");
          break;
        }
      }
    },
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: {}
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类失败，请重试!");
      this.cateList = res.data;
    },
    cateChange() {
      if (this.addGoodsCateSelectedKeys.length !== 3) {
        this.addGoodsTabForm.goods_cat = "";
        this.addGoodsCateSelectedKeys = [];
        return this.$message.error("请选择三级分类");
      }
      // 如果直接使用addGoodsTabForm.goods_cat绑定到级联选择器的v-model，在发起添加商品请求之前需要将其转换为字符串，但级联选择器只允许绑定数组，此时可安装lodash运行依赖，使用其cloneDeep()方法对其进行深拷贝，使用拷贝的对象来当作参数发起请求
      this.addGoodsTabForm.goods_cat = this.addGoodsCateSelectedKeys.join(",");
    },
    async getParams(sel) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel }
        }
      );

      if (res.meta.status !== 200) {
        console.log(res);
        return this.$message.error("获取参数失败，请重试!");
      }
      if (sel === "many") {
        res.data.forEach((item) => {
          if (item.attr_vals) {
            item.attr_vals = item.attr_vals.split(" ");
          } else {
            item.attr_vals = [];
          }
        });
        this.manyParams = res.data;
        console.log(res.data);
      } else {
        this.onlyParams = res.data;
        console.log(this.onlyParams);
      }
    },
    handlePreview(file) {
      // 替换路径
      this.picsUrl = file.response.data.url.replace(
        "http://127.0.0.1:8888",
        "https://lianghj.top:8888"
      );
      this.previewDialog = true;
    },
    uploadPics(res) {
      if (res.meta.status !== 200)
        return this.$message.error("上传图片失败，请重试。");
      this.addGoodsTabForm.pics.push({
        pics: res.data.tmp_path
      });
    },
    removePics(f) {
      const removeIndex = this.addGoodsTabForm.pics.indexOf(
        f.response.data.tmp_path
      );
      this.addGoodsTabForm.pics.splice(removeIndex, 1);
    },
    addGoods() {
      this.$refs.addGoodsTabRef.validate(async (valid) => {
        if (!valid)
          return this.$message.error("表单验证失败，请检查表单后重试!");
        this.manyParams.forEach((item) => {
          this.addGoodsTabForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          });
        });
        this.onlyParams.forEach((item) => {
          this.addGoodsTabForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          });
        });
        const { data: res } = await this.$http.post(
          "goods",
          this.addGoodsTabForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品失败，请重试!");
        }
        this.$message.success("添加商品成功!");
        this.$router.push("/goods");
      });
    }
  },
  computed: {
    cateId() {
      if (this.addGoodsCateSelectedKeys.length) {
        return this.addGoodsCateSelectedKeys[
          this.addGoodsCateSelectedKeys.length - 1
        ];
      }
      return null;
    }
  }
};
</script>

<style lang="less" scoped>
.stepRow {
  margin: 15px 0;
}

/* 防止Tabs组件出现蓝色边框*/
/deep/.el-tabs__item:focus.is-active.is-focus:not(:active) {
  box-shadow: none;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}
.el-checkbox {
  margin-left: 0 !important;
  margin-right: 10px;
}

.el-dialog {
  .previewPics {
    width: 100%;
  }
}

.addGoodsRow {
  margin-top: 15px;
}
</style>
